﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Blog.Framework.Attributes;
using Blog.Framework.DataAccess;
using Blog.Framework.Models;
using Blog.Framework.Utility;

namespace Blog.Web.Controllers
{
    [Layout("Blog")]
    public class BlogController : Controller, IDisposable
    {
        readonly int POSTS_PER_PAGE = 5;
        //readonly int RECENT_ARCHIVES_PER_PAGE = 1;

        IDataProvider mDataProvider;

        public BlogController(IDataProvider dataProvider)
        {
            mDataProvider = dataProvider;
        }

        public BlogController() : this(new DataProvider())
        {
        }

        public ActionResult Index(int? page)
        {
            if (!page.HasValue)
                page = 0;

            PopulateLayoutData();

            ViewData["posts"] = Provider.GetRecentPostSummary(page.Value, POSTS_PER_PAGE);


            // Add action logic here
            return View();
        }

        public ActionResult ViewPost(string url)
        {
            PopulateLayoutData();

            // Add action logic here
            ViewData["post"] = Provider.GetPostForUrl(url);
            return View();
        }

        public ActionResult Archive(int? year, int? month, int?page)
        {
            PopulateLayoutData();

            ViewData["year"] = year.Value;
            ViewData["month"] = month.Value;
            ViewData["monthname"] = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(month.Value);
            ViewData["posts"] = Provider.GetPostsForMonth(month.Value, year.Value, page.Value, POSTS_PER_PAGE);

            // Add action logic here
            return View();
        }

        public ActionResult Tag(string tag, int? page)
        {
            tag = HttpUtility.UrlDecode(tag);

            PopulateLayoutData();

            ViewData["tag"] = tag;
            ViewData["posts"] = Provider.GetPostsForTag(tag, page.Value, POSTS_PER_PAGE);

            // Add action logic here
            return View();
        }

        void PopulateLayoutData()
        {
            ViewData["title"] = "Blog Title";
            ViewData["subtitle"] = "Subtitle goes here";
            ViewData["tagcloud"] = Provider.GetTagCloud();
            ViewData["recentarchivecounts"] = Provider.GetArchiveCounts();
        }

        IDataProvider Provider
        {
            get { return mDataProvider; }
        }

        [NonAction]
        new void Dispose()
        {
            base.Dispose();

            IDisposable disposable = mDataProvider as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }

        [NonAction]
        void IDisposable.Dispose()
        {
            Dispose();
        }
    }
}
